package model.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

public class Factory {

	protected EntityManager em = PersistenceManager.getInstance()
			.getEntityManagerFactory().createEntityManager();

	protected EntityTransaction t = em.getTransaction();

	public void create(Object objeto) {
		try {
			try {
				t.begin();
				em.persist(objeto);
				t.commit();

			} finally {
				if (t.isActive())
					t.rollback();
			}
		} finally {
			em.close();
		}
	}

	public void update(Object objeto) {
		try {
			try {
				t.begin();
				em.merge(objeto);
				t.commit();

			} finally {
				if (t.isActive())
					t.rollback();
			}
		} finally {
			em.close();
		}
	}
	
	public void delete(Object objeto, int id) {
		try {
			t.begin();
			objeto = em.find(objeto.getClass(), id);
			em.remove(objeto);
			t.commit();
		} finally {
			em.close();
		}
	}

	public Object findById(Object classe, int id) {
		Object retorno = null;
		try {

			t.begin();
			retorno = em.find(classe.getClass(), id);
			t.commit();

		} finally {
			//em.close();
			// ver com professor o pq gera erro
		}
		return retorno;
	}

}